package com.sixth.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.sixth.bean.*;
import com.sixth.bean.bo.*;
import com.sixth.bean.common.BasePageInfo;
import com.sixth.bean.common.BasePageInfoVo;
import com.sixth.bean.vo.*;
import com.sixth.constant.Constant;
import com.sixth.exception.DataUpdateException;
import com.sixth.mapper.*;
import com.sixth.other.MarketFreight;
import com.sixth.service.AdminConfigService;
import com.sixth.service.OrderService;
import com.sixth.util.ConfigUtils;
import com.sixth.util.MarketInfoUtil;
import lombok.SneakyThrows;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;


/**
 * @Author lixinhang
 * @Time 2022/9/7 17:26
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    MarketOrderMapper marketOrderMapper;
    @Autowired
    MarketUserMapper marketUserMapper;
    @Autowired
    MarketCommentMapper marketCommentMapper;
    @Autowired
    MarketOrderGoodsMapper marketOrderGoodsMapper;
    @Autowired
    MarketAddressMapper marketAddressMapper;
    @Autowired
    MarketCartMapper marketCartMapper;
    @Autowired
    MarketCouponMapper marketCouponMapper;
    @Autowired
    MarketCouponUserMapper marketCouponUserMapper;
    @Autowired
    MarketSystemMapper marketSystemMapper;
    @Autowired
    AdminConfigService adminConfigService;
    @Autowired
    MarketGrouponRulesMapper marketGrouponRulesMapper;
    @Autowired
    MarketGoodsProductMapper marketGoodsProductMapper;


    //查询符合条件的订单
    // where order_status in orderStatuesArray and user_id=userId and order_sn=orderSn and add_time >= start and add_time <= end
    @Override
    public OrderListVO orderList(OrderListBO orderListBO) {
        BasePageInfo basePageInfo = orderListBO.getBasePageInfo();
        PageHelper.startPage(basePageInfo.getPage(), basePageInfo.getLimit());

        MarketOrderExample marketOrderExample = new MarketOrderExample();
        marketOrderExample.setDistinct(true);
        marketOrderExample.setOrderByClause(basePageInfo.getSort() + " " + basePageInfo.getOrder());    //add_time desc

        MarketOrderExample.Criteria criteria = marketOrderExample.createCriteria();//这个实例里封装了criterion的实例
        //user_id等于
        if (orderListBO.getUserId() != null) {
            criteria.andUserIdEqualTo(orderListBO.getUserId());
        }
        //order_sn等于
        if (!StringUtil.isEmpty(orderListBO.getOrderSn())) {
            criteria.andOrderSnEqualTo(orderListBO.getOrderSn());
        }
        //order_status in
        if (orderListBO.getOrderStatusArray() != null) {
            criteria.andOrderStatusIn(Arrays.asList(orderListBO.getOrderStatusArray()));
        }
        Date start = orderListBO.getStart();
        Date end = orderListBO.getEnd();
        //add_time >=
        if (start != null) {
            criteria.andAddTimeGreaterThanOrEqualTo(start);
        }
        //add_time <=
        if (end != null) {
            criteria.andAddTimeLessThanOrEqualTo(end);
        }
        //deleted位要为0才可以 false--0--未被删除
        criteria.andDeletedEqualTo(false);

        List<MarketOrder> marketOrders = marketOrderMapper.selectByExample(marketOrderExample);
        PageInfo pageInfo = new PageInfo(marketOrders);

        LinkedList<OrderOfOrderListVO> list = new LinkedList<>();
        for (MarketOrder marketOrder : marketOrders) {
            OrderOfOrderListVO orderOfOrderListVO = new OrderOfOrderListVO();
            try {
                BeanUtils.copyProperties(orderOfOrderListVO, marketOrder);
            } catch (Exception e) {
                e.printStackTrace();
            }
            list.add(orderOfOrderListVO);
        }

        Integer total = (int) (pageInfo.getTotal());
        Integer pages = pageInfo.getPages();
        Integer limit = pageInfo.getPageSize();
        Integer page = pageInfo.getPageNum();

        return new OrderListVO(total, pages, limit, page, list);
    }

    @Override
    public OrderDetailVO orderDetail(Integer id) {
        MarketOrderExample marketOrderExample = new MarketOrderExample();
        MarketOrderExample.Criteria criteria = marketOrderExample.createCriteria();
        criteria.andDeletedEqualTo(false);//未被删除
        criteria.andIdEqualTo(id);               //按照id查询
        List<MarketOrder> marketOrders = marketOrderMapper.selectByExample(marketOrderExample);
        if (marketOrders.size() == 0) {
            return null;
        }

        MarketOrder marketOrder = marketOrders.get(0);
        MarketUser marketUser = marketUserMapper.selectByPrimaryKey(marketOrder.getUserId());
        UserOfOrderDetailVO userOfOrderDetailVO = new UserOfOrderDetailVO(marketUser.getNickname(), marketUser.getAvatar());
        OrderOfOrderDetailVO orderOfOrderDetailVO = new OrderOfOrderDetailVO();
        try {
            BeanUtils.copyProperties(orderOfOrderDetailVO, marketOrder);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //根据order_id查询order_goods表，
        MarketOrderGoodsExample marketOrderGoodsExample = new MarketOrderGoodsExample();
        marketOrderGoodsExample.setDistinct(true);
        marketOrderGoodsExample.setOrderByClause("goods_id asc");
        MarketOrderGoodsExample.Criteria marketOrderGoodsExampleCriteria = marketOrderGoodsExample.createCriteria();
        marketOrderGoodsExampleCriteria.andOrderIdEqualTo(id);
        marketOrderGoodsExampleCriteria.andDeletedEqualTo(false);
        List<MarketOrderGoods> marketOrderGoodsList = marketOrderGoodsMapper.selectByExample(marketOrderGoodsExample);
        List<GoodsOfOrderDetailVO> orderGoods = new LinkedList<>();
        for (MarketOrderGoods marketOrderGoods : marketOrderGoodsList) {
            GoodsOfOrderDetailVO goodsOfOrderDetailVO = new GoodsOfOrderDetailVO();
            try {
                BeanUtils.copyProperties(goodsOfOrderDetailVO, marketOrderGoods);
            } catch (Exception e) {
                e.printStackTrace();
            }
            orderGoods.add(goodsOfOrderDetailVO);
        }
        return new OrderDetailVO(orderGoods, userOfOrderDetailVO, orderOfOrderDetailVO);
    }

    //根据订单编号删除订单，实际是修改状态位为1，不只是删除order表，还要删除order_goods表
    @Transactional
    @Override
    public void orderDeleteById(Integer orderId) {
        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setDeleted(true);
        marketOrder.setId(orderId);
        marketOrder.setUpdateTime(new Date());
        marketOrderMapper.updateByPrimaryKeySelective(marketOrder);

        MarketOrderGoods marketOrderGoods = new MarketOrderGoods();
        marketOrderGoods.setDeleted(true);
        marketOrderGoods.setUpdateTime(new Date());
        MarketOrderGoodsExample marketOrderGoodsExample = new MarketOrderGoodsExample();
        MarketOrderGoodsExample.Criteria marketOrderGoodsExampleCriteria = marketOrderGoodsExample.createCriteria();
        marketOrderGoodsExampleCriteria.andOrderIdEqualTo(orderId);
        marketOrderGoodsMapper.updateByExampleSelective(marketOrderGoods, marketOrderGoodsExample);
    }

    //发货->修改shipChannel、shipSn、ship_time、update_time
    @Override
    public void orderShip(Map map) {
        MarketOrder marketOrder = new MarketOrder();
        try {
            BeanUtils.populate(marketOrder, map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        marketOrder.setId((int) map.get("orderId")); //我真的不想写魔法值
        marketOrder.setOrderStatus(Constant.SHIPPED);
        marketOrder.setUpdateTime(new Date());
        marketOrder.setShipTime(new Date());
        marketOrderMapper.updateByPrimaryKeySelective(marketOrder);
    }

    //商家后台同意退款，需要修改order_status,refund_time,refund_amount,update_time
    @Override
    public void orderRefund(OrderRefundBO orderRefundBO) {
        MarketOrder marketOrder = new MarketOrder(orderRefundBO.getOrderId(), Constant.REFUNDED, orderRefundBO.getRefundMoney(), new Date(), new Date());
        marketOrderMapper.updateByPrimaryKeySelective(marketOrder);
    }

    @Override
    public BasePageInfoVo wxList(WXOrderListBO wxOrderListBO) {
        PageHelper.startPage(wxOrderListBO.getPage(), wxOrderListBO.getLimit());

        MarketUser marketUser = MarketInfoUtil.getMarketUser();
        Integer userId = marketUser.getId();
        List<WXOrderListVO> wxOrderListVO = marketOrderMapper.selectAllByStatus(wxOrderListBO.getShowType(), userId);

        PageInfo<WXOrderListVO> wxOrderListVOPageInfo = new PageInfo<>(wxOrderListVO);

        BasePageInfoVo<WXOrderListVO> wxOrderListVOBasePageInfoVo = new BasePageInfoVo<>();
        wxOrderListVOBasePageInfoVo.setLimit(wxOrderListVOPageInfo.getPageSize());
        wxOrderListVOBasePageInfoVo.setPage(wxOrderListVOPageInfo.getPageNum());
        wxOrderListVOBasePageInfoVo.setPages(wxOrderListVOPageInfo.getPages());
        wxOrderListVOBasePageInfoVo.setTotal(wxOrderListVOPageInfo.getTotal());
        wxOrderListVOBasePageInfoVo.setList(wxOrderListVO);


        return wxOrderListVOBasePageInfoVo;
    }

    /**
     * @param commentId
     * @param content
     * @return int
     * @author qys
     * @date 2022/9/9 17:56
     */
    @Transactional
    @Override
    public int adminOrderReply(Integer commentId, String content) {
        // 先查询是否已评论
        MarketComment temp = marketCommentMapper.selectByPrimaryKey(commentId);
        String tempContent = temp.getAdminContent();
        if (!"".equals(tempContent)) {
            return 622;
        }
        // 更改update，adminComment，type
        MarketComment marketComment = new MarketComment();
        marketComment.setUpdateTime(new Date());
        marketComment.setAdminContent(content);
        // 设置已评论
        // marketComment.setType();
        MarketCommentExample marketCommentExample = new MarketCommentExample();
        MarketCommentExample.Criteria marketCommentExampleCriteria = marketCommentExample.createCriteria();
        marketCommentExampleCriteria.andIdEqualTo(commentId);
        marketCommentExampleCriteria.andDeletedEqualTo(Constant.EXIST);
        marketCommentMapper.updateByExampleSelective(marketComment, marketCommentExample);
        return 0;
    }


    /**
     * @param wxOrderCommentBO
     * @return int
     * @author qys
     * @date 2022/9/11 1:22
     */
    @Transactional
    @Override
    public int wxOrderComment(WXOrderCommentBO wxOrderCommentBO) {
        // 先根据orderGoodsId查询出goodsId，orderId
        MarketOrderGoodsExample marketOrderGoodsExample = new MarketOrderGoodsExample();
        MarketOrderGoodsExample.Criteria marketOrderGoodsExampleCriteria = marketOrderGoodsExample.createCriteria();
        marketOrderGoodsExampleCriteria.andIdEqualTo(wxOrderCommentBO.getOrderGoodsId());
        // -1超期不能评论
        marketOrderGoodsExampleCriteria.andCommentNotEqualTo(-1);
        marketOrderGoodsExampleCriteria.andDeletedEqualTo(Constant.EXIST);
        List<MarketOrderGoods> marketOrderGoodsTemp = marketOrderGoodsMapper.selectByExample(marketOrderGoodsExample);
        if (marketOrderGoodsTemp.size() == 0) {
            return 614;
        }
        MarketOrderGoods marketOrderGoods = marketOrderGoodsTemp.get(0);
        // 获得goodsId插入comment表
        Integer goodsId = marketOrderGoods.getGoodsId();
        MarketComment marketComment = new MarketComment();
        marketComment.setValueId(goodsId);
        String[] picUrls = wxOrderCommentBO.getPicUrls();
        // 不传图片不插入
        if (picUrls != null && picUrls.length != 0) {
            marketComment.setHasPicture(true);
            marketComment.setPicUrls(picUrls);
        }
        marketComment.setContent(wxOrderCommentBO.getContent());
        marketComment.setStar(wxOrderCommentBO.getStar());
        marketComment.setAddTime(new Date());
        // TODO : type专题类型，和userId，某个表中信息逻辑删除时修改不成功的响应信息
        MarketUser marketUser = MarketInfoUtil.getMarketUser();
        marketComment.setUserId(marketUser.getId());
        marketComment.setType((byte) 0);
        marketCommentMapper.insertSelective(marketComment);
        // 获得自增的主键
        Integer commentId = marketComment.getId();
        // 修改orderGoods表中的comment,updateTime
        MarketOrderGoods updateMarketOrderGoodsTemp = new MarketOrderGoods();
        updateMarketOrderGoodsTemp.setUpdateTime(new Date());
        updateMarketOrderGoodsTemp.setComment(commentId);
        // 设置条件
        MarketOrderGoodsExample updateMarketOrderGoods = new MarketOrderGoodsExample();
        MarketOrderGoodsExample.Criteria updateMarketOrderGoodsCriteria = updateMarketOrderGoods.createCriteria();
        updateMarketOrderGoodsCriteria.andDeletedEqualTo(Constant.EXIST);
        updateMarketOrderGoodsCriteria.andIdEqualTo(wxOrderCommentBO.getOrderGoodsId());
        marketOrderGoodsMapper.updateByExampleSelective(updateMarketOrderGoodsTemp, updateMarketOrderGoods);
        Integer orderId = marketOrderGoods.getOrderId();
        // 修改order表
        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setUpdateTime(new Date());
        marketOrder.setId(orderId);
        // 查出order中为评价的数量,如果只剩一个商品未评价，将status改为403
        MarketOrder marketOrderTemp = marketOrderMapper.selectNonDeletedByPrimaryKey(orderId, Constant.EXIST);
        if (marketOrderTemp.getComments() == 1) {
            marketOrder.setOrderStatus((short) 403);
        }
        // comments是order表中为评价的商品数量，评论后-1
        int affectRow = marketOrderMapper.updateComment(marketOrder);
        return 0;
    }

    @Transactional
    @Override
    public int wxRefund(int orderId) {


        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setId(orderId);
        marketOrder.setOrderStatus((short) 202);
        marketOrder.setAftersaleStatus((short) 1);

        int code = marketOrderMapper.updateByPrimaryKeySelective(marketOrder);

        if (code == 0) {
            return 404;
        }

        return 200;
    }

    @SneakyThrows
    @Override
    public WXOrderDetailVO wxDetail(int orderId) {

        //查询订单信息(deleted == 0)
        MarketOrder marketOrder = marketOrderMapper.selectNonDeletedByPrimaryKey(orderId, Constant.EXIST);

        if (marketOrder == null) {
            return null;
        }
        WXOrderDetailVO wxOrderDetailVO = new WXOrderDetailVO();
        //封装订单信息
        OrderInfoBean orderInfoBean = new OrderInfoBean();
        HandleOptionBean handlerOption = getHandlerOption(marketOrder.getOrderStatus());
        BeanUtils.copyProperties(orderInfoBean, marketOrder);
        orderInfoBean.setExpCode(marketOrder.getShipSn());
        orderInfoBean.setOrderStatusText(Constant.ORDER_STATUS.get(marketOrder.getOrderStatus()));
        orderInfoBean.setExpNo(marketOrder.getShipSn());
        orderInfoBean.setExpName(Constant.CODE_NAME_MAP.get(marketOrder.getShipChannel()));
        orderInfoBean.setHandleOption(handlerOption);

        wxOrderDetailVO.setOrderInfo(orderInfoBean);

        //-------------------------------------------------分割线

        //查询订单中的商品信息
        List<MarketOrderGoods> marketOrderGoods = marketOrderGoodsMapper.selectByOrderId(orderId);
        if (marketOrderGoods.size() == 0) {
            return null;
        }
        //封装订单商品信息
        List<OrderGoodsBean> orderGoodsList = new ArrayList<>();
        for (MarketOrderGoods marketOrderGood : marketOrderGoods) {
            OrderGoodsBean orderGoodsBean = new OrderGoodsBean();
            BeanUtils.copyProperties(orderGoodsBean, marketOrderGood);
            orderGoodsList.add(orderGoodsBean);
        }
        wxOrderDetailVO.setOrderGoods(orderGoodsList);

        return wxOrderDetailVO;
    }

    @Transactional
    @Override
    public int wxDelete(int orderId) {

        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setId(orderId);
        marketOrder.setDeleted(Constant.NOEXIST);
        int code = marketOrderMapper.updateByPrimaryKeySelective(marketOrder);
        if (code == 0) {
            return 404;
        }

        return 200;
    }

    @Transactional
    @Override
    public int wxConfirm(int orderId) {

        MarketOrder marketOrder = marketOrderMapper.selectByPrimaryKey(orderId);
        //修改待评论数
        int comments = marketOrderGoodsMapper.selectInWXConfirm(orderId);
        marketOrder.setId(orderId);
        marketOrder.setOrderStatus((short) 401);
        marketOrder.setComments((short) comments);
        int code = marketOrderMapper.updateByPrimaryKeySelective(marketOrder);
        if (code == 0) {
            return 404;
        }


        return 200;
    }

    @Transactional
    @Override
    public int wxCancel(int orderId) {
        //需要修改status为102即可
        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setId(orderId);
        marketOrder.setOrderStatus((short) 102);
        int code = marketOrderMapper.updateByPrimaryKeySelective(marketOrder);
        if (code == 0) {
            return 404;
        }
        //修改库存信息
        List<MarketOrderGoods> marketOrderGoods = marketOrderGoodsMapper.selectByOrderId(orderId);
        for (MarketOrderGoods marketOrderGood : marketOrderGoods) {
            MarketGoodsProduct marketGoodsProduct
                    = marketGoodsProductMapper.selectByPrimaryKey(marketOrderGood.getProductId());
            if (marketGoodsProduct == null) {
                throw new DataUpdateException("更新数据失败");
            }
            marketGoodsProduct.setNumber(marketGoodsProduct.getNumber() + marketOrderGood.getNumber());
            code = marketGoodsProductMapper.updateByPrimaryKeySelective(marketGoodsProduct);
            if (code == 0) {
                throw new DataUpdateException("更新数据失败");
            }
        }
        // //修改优惠券信息
        // marketOrder = marketOrderMapper.selectByPrimaryKey(orderId);
        // if(!marketOrder.getCouponPrice().equals(BigDecimal.ZERO)){
        //     code = marketCouponUserMapper.updateInCancelByOrderId(orderId);
        //     if(code == 0){
        //
        //     }
        // }
        return 200;
    }

    @Transactional
    @Override
    public int wxPrepay(int orderId) {

        //先check订单是否过期
        MarketOrder marketOrder = marketOrderMapper.selectByPrimaryKey(orderId);
        if (marketOrder.getEndTime().getTime() < System.currentTimeMillis()) {
            return 405;
        }
        //需要修改status为201即可
        marketOrder = new MarketOrder();
        marketOrder.setId(orderId);
        marketOrder = marketOrderMapper.selectByPrimaryKey(orderId);
        marketOrder.setOrderStatus((short) 201);
        marketOrder.setPayTime(new Date());

        int code = marketOrderMapper.updateByPrimaryKeySelective(marketOrder);
        if (code == 0) {
            return 404;
        }

        //修改库存
        List<MarketOrderGoods> marketOrderGoods = marketOrderGoodsMapper.selectByOrderId(orderId);
        for (MarketOrderGoods marketOrderGood : marketOrderGoods) {
            MarketGoodsProduct marketGoodsProduct
                    = marketGoodsProductMapper.selectByPrimaryKey(marketOrderGood.getProductId());
            //削减数量
            if (marketGoodsProduct == null) {
                throw new DataUpdateException("更新失败");
            }
            marketGoodsProduct.setNumber(marketGoodsProduct.getNumber() - marketOrderGood.getNumber());
            code = marketGoodsProductMapper.updateByPrimaryKeySelective(marketGoodsProduct);
            if (code == 0) {
                throw new DataUpdateException("更新失败");
            }
        }

        return 200;
    }

    @SneakyThrows
    @Transactional
    @Override
    public WXOrderSubmitVO wxSubmit(WXOrderSubmitBo wxOrderSubmitBo) {
        //查询地址的信息
        MarketAddress marketAddress
                = marketAddressMapper.selectByPrimaryKey(wxOrderSubmitBo.getAddressId());
        //查询cart信息
        MarketCart marketCart = null;
        List<MarketCart> marketCarts = null;
        if (wxOrderSubmitBo.getCartId() != 0) {
            marketCart = marketCartMapper.selectByPrimaryKey(wxOrderSubmitBo.getCartId());
        } else {
            MarketCartExample marketCartExample = new MarketCartExample();
            MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
            criteria.andUserIdEqualTo(MarketInfoUtil.getMarketUser().getId());
            criteria.andCheckedEqualTo(Constant.SELECTED);
            criteria.andDeletedEqualTo(Constant.EXIST);
            marketCarts = marketCartMapper.selectByExample(marketCartExample);
        }
        //查询用户的优惠券信息
        //查询优惠券信息
        MarketCoupon marketCoupon = null;
        MarketCouponUser marketCouponUser = null;
        BigDecimal couponPrice = BigDecimal.ZERO;
        if (wxOrderSubmitBo.getCouponId() != 0 && wxOrderSubmitBo.getCouponId() != -1) {
            marketCouponUser = marketCouponUserMapper.selectByPrimaryKey(wxOrderSubmitBo.getUserCouponId());
            marketCoupon = marketCouponMapper.selectByPrimaryKey(wxOrderSubmitBo.getCouponId());
            couponPrice = marketCoupon.getDiscount();

        }
        //查询商城运费配置信息
        List<MarketSystem> marketSystems = adminConfigService.select(MarketFreight.list);
        ConfigExpressVO configExpressVO = new ConfigExpressVO();
        ConfigUtils.getConfig(marketSystems, configExpressVO);
        //如果团购id不为0查询团购信息
        MarketGrouponRules marketGrouponRules = null;
        BigDecimal groupPrice = BigDecimal.ZERO;
        if (wxOrderSubmitBo.getGrouponRulesId() != 0) {
            marketGrouponRules = marketGrouponRulesMapper.selectByPrimaryKey(wxOrderSubmitBo.getGrouponRulesId());
            groupPrice = marketGrouponRules.getDiscount();
        }


        if (MarketInfoUtil.getMarketUser() == null) {
            return null;
        }
        //先生成订单表
        MarketOrder marketOrder = getMarketOrder(wxOrderSubmitBo, marketAddress, marketCart, couponPrice, configExpressVO, groupPrice, marketCarts);
        int code = marketOrderMapper.insertSelective(marketOrder);
        if (code == 0) {
            return null;
        }
        //生成订单商品表
        ArrayList<MarketOrderGoods> marketOrderGoodsList = getMarketOrderGoods(marketCart, marketCarts, marketOrder);
        code = marketOrderGoodsMapper.insertInSubmit(marketOrderGoodsList);

        if (code != marketOrderGoodsList.size()) {
            throw new DataUpdateException("插入数据不对整");
        }

        //如果有使用优惠券，修改优惠券状态
        if (marketCouponUser != null) {
            marketCouponUser.setStatus((short) 1);
            marketCouponUser.setUsedTime(new Date());
            marketCouponUser.setOrderId(marketOrder.getId());
            code = marketCouponUserMapper.updateByPrimaryKeySelective(marketCouponUser);
            if (code == 0) {
                return null;
            }
        }

        WXOrderSubmitVO wxOrderSubmitVO = new WXOrderSubmitVO();
        wxOrderSubmitVO.setGrouponLinkId(wxOrderSubmitBo.getGrouponLinkId());
        wxOrderSubmitVO.setOrderId(marketOrder.getId());
        return wxOrderSubmitVO;
    }

    @SneakyThrows
    @Override
    public WXOrderGoodsVO wxGoods(WXOrderGoodsBO wxOrderGoodsBO) {

        MarketOrderGoodsExample marketOrderGoodsExample = new MarketOrderGoodsExample();
        MarketOrderGoodsExample.Criteria criteria = marketOrderGoodsExample.createCriteria();
        criteria.andOrderIdEqualTo(wxOrderGoodsBO.getOrderId());
        criteria.andGoodsIdEqualTo(wxOrderGoodsBO.getGoodsId());
        criteria.andDeletedEqualTo(false);
        //只会查到一条数据
        List<MarketOrderGoods> marketOrderGoods = marketOrderGoodsMapper.selectByExample(marketOrderGoodsExample);
        if (marketOrderGoods.size() == 0) {
            return null;
        }
        MarketOrderGoods goodsInfo = marketOrderGoods.get(0);
        WXOrderGoodsVO wxOrderGoodsVO = new WXOrderGoodsVO();
        BeanUtils.copyProperties(wxOrderGoodsVO, goodsInfo);

        return wxOrderGoodsVO;
    }

    private ArrayList<MarketOrderGoods> getMarketOrderGoods(MarketCart marketCart, List<MarketCart> marketCarts, MarketOrder marketOrder) throws IllegalAccessException, InvocationTargetException {
        ArrayList<MarketOrderGoods> marketOrderGoodsList = new ArrayList<>();
        if (marketCarts == null) {
            marketCarts = new ArrayList<>();
            marketCarts.add(marketCart);
        }
        for (MarketCart cart : marketCarts) {
            MarketOrderGoods marketOrderGoods = new MarketOrderGoods();
            BeanUtils.copyProperties(marketOrderGoods, cart);
            marketOrderGoods.setOrderId(marketOrder.getId());
            // marketOrderGoods.setOrderId(marketOrder.getId());
            // marketOrderGoods.setGoodsId(cart.getGoodsId());
            // marketOrderGoods.setGoodsName(cart.getGoodsName());
            // marketOrderGoods.setGoodsSn(cart.getGoodsSn());
            // marketOrderGoods.setProductId(cart.getProductId());
            // marketOrderGoods.setNumber(cart.getNumber());
            // marketOrderGoods.setPrice(cart.getPrice());
            // marketOrderGoods.setSpecifications(cart.getSpecifications());
            // marketOrderGoods.setPicUrl(cart.getPicUrl());
            marketOrderGoods.setAddTime(new Date());
            marketOrderGoods.setUpdateTime(new Date());
            marketOrderGoodsList.add(marketOrderGoods);
        }
        return marketOrderGoodsList;
    }


    private MarketOrder getMarketOrder(WXOrderSubmitBo wxOrderSubmitBo, MarketAddress marketAddress, MarketCart marketCart, BigDecimal couponPrice, ConfigExpressVO configExpressVO, BigDecimal groupPrice, List<MarketCart> marketCarts) {
        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setUserId(MarketInfoUtil.getMarketUser().getId());
        marketOrder.setOrderSn(getOrderSn());
        marketOrder.setOrderStatus((short) 101);
        marketOrder.setAftersaleStatus((short) 0);
        marketOrder.setConsignee(marketAddress.getName());
        marketOrder.setMobile(MarketInfoUtil.getMarketUser().getMobile());
        marketOrder.setAddress(marketAddress.getCounty() + marketAddress.getCity() + " " + marketAddress.getAddressDetail());
        marketOrder.setMessage(wxOrderSubmitBo.getMessage());
        //计算商品总价
        BigDecimal totalPrice = BigDecimal.ZERO;
        if (marketCart != null) {
            totalPrice = marketCart.getPrice().multiply(BigDecimal.valueOf(marketCart.getNumber()));
        } else {
            for (MarketCart cart : marketCarts) {
                totalPrice = totalPrice.add(cart.getPrice().multiply(BigDecimal.valueOf(cart.getNumber())));
            }
        }
        marketOrder.setGoodsPrice(totalPrice);
        //将商品总价与商城免运费最低价格比较，返回更高的值，此值如果equals商品总价说明可以免运费
        //注入运费信息
        String minPrice = configExpressVO.getMarket_express_freight_min();
        BigDecimal freightPrice = BigDecimal.ZERO;
        if (!totalPrice.max(BigDecimal.valueOf(Integer.parseInt(minPrice))).equals(totalPrice)) {
            freightPrice = BigDecimal.valueOf(Integer.parseInt(configExpressVO.getMarket_express_freight_value()));
        }
        marketOrder.setFreightPrice(freightPrice);
        //注入优惠券信息
        marketOrder.setCouponPrice(couponPrice);
        //注入积分优惠信息
        BigDecimal integralPrice = BigDecimal.ZERO;
        marketOrder.setIntegralPrice(integralPrice);
        //注入团购信息
        marketOrder.setGrouponPrice(groupPrice);
        //注入订单费用信息:goods_price + freight_price - coupon_price
        BigDecimal orderPrice = totalPrice.add(freightPrice).subtract(couponPrice);
        marketOrder.setOrderPrice(orderPrice);
        //注入真实费用信息: order_price - integral_price
        marketOrder.setActualPrice(orderPrice.subtract(integralPrice));
        //todo：过期时间15分钟
        marketOrder.setEndTime(new Date(System.currentTimeMillis() + Constant.EXPIRATION));

        marketOrder.setAddTime(new Date());
        marketOrder.setUpdateTime(new Date());
        return marketOrder;
    }


    private String getOrderSn() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String date = sdf.format(new Date());
        Random random = new Random();
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < 6; i++) {
            buffer.append(random.nextInt(10));
        }
        return date + buffer;
    }


    private HandleOptionBean getHandlerOption(Short orderStatus) {
        HandleOptionBean handleOption = new HandleOptionBean();

        switch (orderStatus) {
            case 101:
                handleOption.setPay(true);
                handleOption.setCancel(true);
                break;
            case 102:
                handleOption.setCancel(true);
                break;
            case 103:
                handleOption.setCancel(true);
                break;
            case 201:
                handleOption.setRefund(true);
                break;
            case 301:
                handleOption.setConfirm(true);
                break;
            case 401:
                handleOption.setDelete(true);
                handleOption.setComment(true);
                handleOption.setRebuy(true);
                handleOption.setAftersale(true);
                break;
            case 402:
                handleOption.setDelete(true);
                handleOption.setComment(true);
                handleOption.setRebuy(true);
                handleOption.setAftersale(true);
                break;
            case 403:
                handleOption.setDelete(true);
                handleOption.setRebuy(true);
                handleOption.setAftersale(true);
        }
        return handleOption;

    }
}
